<template>
  <view>
    <z-paging
      ref="paging"
      class="material-list"
      v-model="materialList"
      :default-page-size="limit"
      :use-page-scroll="true"
      :to-bottom-loading-more-enabled="true"
      :auto="false"
      :fixed="false"
      :min-delay="800"
      :show-loading-more-no-more-view="false"
      :auto-hide-loading-after-first-loaded="false"
      :refresher-enabled="false"
      @query="getData"
    >
      <view class="material-box" v-for="(material, index) in materialList" :key="index">
        <view class="material-item">
          <view class="material-left">
            <image
              class="user-avatar"
              :src="avatar || config.custom.avatar"
              @error="avatar = config.custom.avatar"
            />
          </view>
          <view class="material-right">
            <text class="user-name">{{ fansStore.fansinfo.nickname || '用户' }}</text>

            <mt-tool-collapse
              class="flex pt-8rpx"
              :content="material.content"
              :size="30"
              :row="4"
              @clickText="gotoDetail(material.id)"
            ></mt-tool-collapse>

            <view class="pt-25rpx">
              <view class="image-box" v-if="material.media_type == 1">
                <image
                  v-for="(item, idx) in material.media_urls.split(',')"
                  mode="aspectFill"
                  lazy-load
                  :lazy-load-margin="0"
                  :src="`${item}?imageView2/0/w/300/h/300`"
                  :key="idx"
                  @click="preview(idx, material.media_urls)"
                ></image>
              </view>
              <view class="video-box" v-if="material.media_type == 2">
                <video :src="material.media_urls"></video>
              </view>
            </view>
          </view>
        </view>
        <view>
          <view class="icon-box">
            <text
              class="copy-btn"
              :class="material.is_copy ? 'copy-btn-show' : 'copy-btn-close'"
              @click="copyArticle(material)"
            >
              复制图文
            </text>
            <view class="more-bg" @click="material.is_copy = !material.is_copy">
              <u-icon class="more-btn" custom-prefix="mt-icon" :size="40" name="more"></u-icon>
            </view>
          </view>
          <view class="relate-box" v-if="material.relate_id > 0" @click="gotoGoods(material.relate_id)">
            <view class="flex">
              <image :src="material.relate_info.goods_logo"></image>
            </view>
            <view class="relate-area">
              <text class="relate-title line-1">{{ material.relate_info.goods_name }}</text>
              <view class="price">￥{{ material.relate_info.goods_specs[0].goods_price }}</view>
            </view>
          </view>
        </view>
      </view>
      <template #loading>
        <view class="loading">
          <mt-logo-loading :size="88"></mt-logo-loading>
        </view>
      </template>
    </z-paging>

    <!-- 遮罩层 -->
    <view
      class="fixed top-0 left-0 right-0 bottom-0 h-full flex items-center justify-center"
      v-show="maskShow"
    >
      <view class="circle-box">
        <u-circle-progress
          :active-color="config.theme.bg_light"
          :percent="percent"
          width="180"
          bg-color="rgba(0, 0, 0, 0)"
        >
          <view class="flex flex-col items-center color-white">
            <text class="font-size-26rpx">下载中</text>
            <text class="font-size-23rpx u-progress-info">{{ percentLabel }}</text>
          </view>
        </u-circle-progress>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import MtToolCollapse from '@/components/mt-tool/mt-tool-collapse.vue';
  import MtLogoLoading from '@/components/mt-loading/mt-logo-loading.vue';
  import { getMaterial as getDataApi } from '@/api/material/index';
  import { ref, nextTick } from 'vue';
  import { onLoad, onReachBottom } from '@dcloudio/uni-app';
  import { report } from '@/utils/exception';
  import { msg } from '@/utils/msg';
  import { useFansStore } from '@/store/fans';
  import { config } from '@/config/env';
  import type { MaterialList } from '@/types/material';

  const fansStore = useFansStore();
  const avatar = ref<string>(fansStore.fansinfo.avatar);
  const materialList = ref<MaterialList[]>([]);
  const limit = 8;
  const categoryId = ref<number>(0);
  const materialId = ref<number>(0);
  const maskShow = ref<boolean>(false);
  const percent = ref<number>(0);
  const percentLabel = ref<string>('');
  const search = ref<string>('');
  const paging = ref();

  const getData = (pageNo: number, pageSize: number) => {
    getDataApi(pageNo, pageSize, categoryId.value, materialId.value, search.value)
      .then((res) => {
        res.data.list.forEach((item: MaterialList) => {
          item.is_copy = false;
        });
        paging.value.complete(res.data.list);
      })
      .catch((err) => {
        report(err);
      });
  };

  onReachBottom(() => {
    paging.value.doLoadMore();
  });

  onLoad((option: any) => {
    if (option.category_id) {
      categoryId.value = option.category_id;
    }
    if (option.id) {
      materialId.value = option.id;
    }
    nextTick(() => {
      paging.value.reload();
    });
  });

  // 图片预览
  const preview = (index: number, urls: string) => {
    uni.previewImage({ current: index, urls: urls.split(',') });
  };

  // 复制图文
  const copyArticle = (material: MaterialList) => {
    uni.setClipboardData({
      data: material.content,
      success: () => {
        material.is_copy = !material.is_copy;
        if (material.media_type == 0) {
          return msg.text('素材文字已复制');
        }

        msg.text('素材文字已复制，\n即将下载资源...', 2500);
        const mediaUrls = material.media_urls.split(',');
        const mediaType = material.media_type;
        const index = 0;
        percent.value = 0;
        percentLabel.value = mediaType == 1 ? `0/${mediaUrls.length}` : '0 MB/0 MB';

        setTimeout(() => {
          maskShow.value = true;
          saveAlbum(index, mediaType, mediaUrls);
        }, 2800);
      },
    });
  };

  // 保存媒体资源到相册
  const saveAlbum = (index: number, mediaType: number, mediaUrls: string[]) => {
    if (mediaType == 1) {
      // 图片
      let num = index + 1;
      uni.downloadFile({
        url: mediaUrls[index],
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                percentLabel.value = `${num}/${mediaUrls.length}`;
                if (num < mediaUrls.length) {
                  percent.value = (num / mediaUrls.length) * 100;
                  return ++index && saveAlbum(index, mediaType, mediaUrls);
                }

                percent.value = 100;
                setTimeout(() => {
                  maskShow.value = false;
                  msg.success('素材已下载完毕，\n请查看相册！', 3000);
                }, 800);
              },
              fail: (err) => {
                maskShow.value = false;
                if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
                  // 用户取消保存
                  return;
                }
                msg.error('素材保存相册失败：' + err.errMsg);
              },
            });
          } else {
            maskShow.value = false;
            msg.error('素材下载失败');
          }
        },
        fail: (err) => {
          maskShow.value = false;
          msg.error('素材下载失败：' + err.errMsg);
        },
      });
    } else {
      // 视频
      const downloadTask = uni.downloadFile({
        url: mediaUrls[index],
        success: (res) => {
          if (res.statusCode === 200) {
            // 视频
            uni.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                maskShow.value = false;
                msg.success('素材已下载完毕，\n请查看相册！', 3000);
              },
              fail: (err) => {
                maskShow.value = false;
                if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
                  // 用户取消保存
                  return;
                }
                msg.error('素材保存相册失败：' + err.errMsg);
              },
            });
          } else {
            maskShow.value = false;
            msg.error('素材下载失败');
          }
        },
        fail: (err) => {
          maskShow.value = false;
          msg.error('素材下载失败：' + err.errMsg);
        },
      });

      // 监控下载进度
      downloadTask.onProgressUpdate((res) => {
        percent.value = res.progress;
        percentLabel.value =
          (res.totalBytesWritten / 1024 / 1024).toFixed(1) +
          ' MB/\n' +
          (res.totalBytesExpectedToWrite / 1024 / 1024).toFixed(1) +
          ' MB';
      });
    }
  };

  const gotoDetail = (id: number) => {
    uni.navigateTo({ url: `/pages/material/detail?id=${id}` });
  };

  const gotoGoods = (goodsId: number) => {
    uni.navigateTo({ url: `/pages/goods/detail?id=${goodsId}` });
  };

  const reloadData = (searchKey: string) => {
    search.value = searchKey;
    paging.value.reload();
  };

  defineExpose({
    reloadData,
  });
</script>

<style lang="scss" scoped>
  .material-list {
    .material-box {
      padding: 30rpx 40rpx 20rpx;

      &:not(:last-child) {
        border-bottom: 1px solid #ececec;
      }

      &:last-child {
        padding-bottom: 130rpx;
      }

      .material-item {
        display: flex;

        .material-left {
          padding-right: 20rpx;

          .user-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 10rpx;
          }
        }

        .material-right {
          padding-right: 80rpx;
          padding-bottom: 30rpx;
          flex: 1;

          .user-name {
            font-size: 32rpx;
            font-weight: 600;
            color: #6e76a0;
          }

          .image-box {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            row-gap: 7rpx;

            image {
              width: 160rpx;
              height: 160rpx;
            }
          }

          .video-box {
            video {
              width: 100%;
            }
          }
        }
      }

      .icon-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-bottom: 30rpx;

        .copy-btn {
          font-size: 26rpx;
          background: #3e3e3e;
          padding: 10rpx 20rpx;
          color: #f2f2f2;
          letter-spacing: 2rpx;
          border-radius: 10rpx;
          position: relative;
          transition: all 0.3s ease-in-out;
        }

        .copy-btn-show {
          right: -40rpx;
        }

        .copy-btn-close {
          right: -192rpx;
        }

        .more-bg {
          background: white;
          padding: 10rpx 38rpx 10rpx 20rpx;
          position: relative;
          right: -40rpx;
          .more-btn {
            padding: 0 12rpx;
            background: #f5f5f5;
            border-radius: 10rpx;
          }
        }
      }

      .relate-box {
        display: flex;
        align-items: center;
        padding: 15rpx;
        border-radius: 10rpx;
        box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;

        image {
          width: 80rpx;
          height: 80rpx;
          border-radius: 10rpx;
          margin-right: 15rpx;
        }

        .relate-area {
          .relate-title {
            font-size: 26rpx;
            margin-bottom: 3rpx;
          }
          .price {
            color: $themeColor;
            font-size: 28rpx;
            font-weight: 600;
          }
        }
      }
    }

    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 600rpx;
    }
  }

  .circle-box {
    background: rgba(0, 0, 0, 0.5);
    padding: 5rpx;
    border-radius: 50%;
    backdrop-filter: blur(2px);
  }
</style>
